package com.itcs.netty.controller;

import com.alibaba.fastjson.JSON;
import com.itcs.box.BoxConstants;
import com.itcs.netty.client.ClientNettyChannelMap;
import com.itcs.netty.client.NettyClientBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author LiuPeng
 * 
 */
@RestController
@RequestMapping("/")
public class ClientController {

	private Log logger = LogFactory.getLog(getClass());

	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/send")
	public String send(HttpServletRequest request, HttpServletResponse response) {

		String clientId = request.getParameter("clientId");
		String reqJson = request.getParameter("reqJson");
		
		NettyClientBootstrap client = ClientNettyChannelMap.getClient(clientId);
		if (client == null) {
			return "client[" + clientId + "]未连接到服务器";
		}

		ByteBuf heapBuffer = Unpooled.buffer(8);
		heapBuffer.writeBytes(reqJson.getBytes(BoxConstants.CHARSET_UTF8));

		client.writeAndFlush(heapBuffer);

		logger.info("client[" + client.getClientId() + "]向服务端发送交易-" + JSON.toJSONString(reqJson));

		return "client[" + client.getClientId() + "]成功向服务端发送交易-" + JSON.toJSONString(reqJson);
		
	}

}
